package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.IApCommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApCommentServiceImpl implements IApCommentService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;


    //保存评论数据
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        //判断是否登录
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = new ApComment();
        //apComment.setId();//自动复制
        if (user.getUserId() == 0) {
            apComment.setUserId(user.getUserId());
            apComment.setUserName("游客登录");
            apComment.setImage(null);
        } else {
            ResponseResult<ApUser> responseResult = userFeign.getById(user.getUserId());
            ApUser apUser = responseResult.getData();
            apComment.setUserId(user.getUserId());
            apComment.setUserName(apUser.getName());
            apComment.setImage(apUser.getImage());
        }

        apComment.setArticleId(dto.getArticleId());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setRepay(0);
        apComment.setCreatedTime(new Date());

        mongoTemplate.save(apComment);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult loadComment(CommentDto dto) {
        //判断是否登录
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据文章id查询
        //根据评论数据排序
        //分页条件   评论时间 < minTime

        if (dto.getSize() == null) {
            dto.setSize(10);
        }

        Query query = new Query(Criteria.where("articleId").is(dto.getArticleId())
                .and("createdTime").lt(dto.getMinDate()));
        query.limit(dto.getSize());
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);

        List<ApCommentVo>apCommentVoList=new ArrayList<>();
        //当前登录人是否点过赞
        for (ApComment apComment : apCommentList) {
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment, apCommentVo);
            //0已点赞  1未点赞
            if (redisTemplate.hasKey("comment_like_"+user.getUserId() + "_" + apComment.getId())) {
                apCommentVo.setOperation(0);//已点赞
            }else {
                apCommentVo.setOperation(1);//未点赞
            }
            apCommentVoList.add(apCommentVo);
        }

        return ResponseResult.okResult(apCommentVoList);
    }

    @Override
    public ResponseResult likeComment(CommentLikeDto dto) {
        //判断是否登录
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //0：点赞  1：取消点赞
        if (dto.getOperation() == 0) {
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setUserId(user.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            //0：点赞  1：取消点赞
            apCommentLike.setOperation(dto.getOperation());

            mongoTemplate.save(apCommentLike);

            //修改当前评论的点赞数
            Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes", 1);
            mongoTemplate.updateFirst(query, update, ApComment.class);

            //redis 记录是否点赞
            redisTemplate.boundValueOps("comment_like_" + user.getUserId() + "_" + dto.getCommentId()).set("");


        } else {
            //删除当前用户点赞的数据
            mongoTemplate.remove(new Query(Criteria.where("userId").is(user.getUserId())
                    .and("commentId").is(dto.getCommentId())), ApCommentLike.class);


            //0：点赞  1：取消点赞
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setUserId(user.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);


            Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("likes", -1);
            mongoTemplate.updateFirst(query, update, ApComment.class);
            //取消点赞  删除redis数据
            redisTemplate.delete("comment_like_" + user.getUserId() + "_" + dto.getCommentId());

        }

        return ResponseResult.okResult();
    }
}
